/*
 * @Author: zhangyang
 * @Date: 2020-12-08 11:26:10
 * @LastEditTime: 2021-12-23 12:17:25
 * @Description: HTTP 网络请求模块
 */
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { removeToken } from './auth';

/**
 * 开始加载
 */
const startLoading = () => {
  // 不设超时时间，禁止点击
  Toast.loading({
    duration: 0,
    forbidClick: true,
  });
};
/**
 * 结束加载
 */
const endLoading = () => Toast.clear();
/**
 * 请求地址
 */
let BASE_URL = import.meta.env.VITE_BASE_HTTP;
let mode = import.meta.env.MODE;
const arr = mode.split('.');
if (arr[1]) {
  BASE_URL = `${BASE_URL}/${arr[0]}`;
}
/**
 * 创建 Axios 实例
 */
const net = axios.create({
  baseURL: BASE_URL,
  timeout: 1000 * 5,
});
/**
 * 设置请求拦截器
 */
net.interceptors.request.use(
  (req: AxiosRequestConfig) => {
    startLoading();
    return req;
  },
  (error) => {
    console.error(error);
    Toast.fail(error);
    return Promise.reject(error);
  },
);

enum Status {
  TOKEN_NO_USE = -1,
  OK = 0,
}

interface ResponseObj {
  status: number;
  data: any;
  msg: string;
}

/**
 * 设置响应拦截器
 */
net.interceptors.response.use(
  (response: AxiosResponse<ResponseObj>) => {
    endLoading();
    const res = response.data;
    if (res.status === Status.OK) {
      return res.data;
    } else if (res.status === Status.TOKEN_NO_USE) {
      Dialog.alert({
        message: '登录信息过期，请重新登录！',
      }).finally(() => {
        removeToken();
        location.href = '/base/login';
      });
    } else {
      const ErrMsg = res.msg;
      Toast.fail(ErrMsg);
      throw new Error(ErrMsg);
    }
  },
  (error: Error) => {
    endLoading();
    console.error(error);
    Toast.fail(error.message);
    throw new Error(error.message);
  },
);

export default net;
